package uk.co.wroedevelopments.semanticworkbench.actions;

import org.eclipse.emf.ecore.EObject;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.text.source.ISourceViewer;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.IWorkbenchWindowActionDelegate;
import org.eclipse.xtext.concurrent.IUnitOfWork;
import org.eclipse.xtext.parser.IParseResult;
import org.eclipse.xtext.resource.XtextResource;
import org.eclipse.xtext.ui.core.editor.XtextEditor;
import org.eclipse.xtext.ui.core.editor.XtextSourceViewer;
import org.eclipse.xtext.ui.core.editor.model.XtextDocument;
import org.xtext.example.semQryDsl.Query;

import uk.co.wroedevelopments.semanticworkbench.query.QueryPlan;
import uk.co.wroedevelopments.semanticworkbench.query.QueryUtils;

public class NeoQueryAction implements IWorkbenchWindowActionDelegate {

	private  IWorkbenchWindow window;

	public void dispose() {
		// TODO Auto-generated method stub

	}

	public void init(IWorkbenchWindow window) {
		this.window = window;

	}

	public void run(IAction arg0) {
		try {

			
			IEditorPart ed = window.getActivePage().getActiveEditor();
			if (ed instanceof XtextEditor) {
				XtextEditor xed = (XtextEditor) ed;
				ISourceViewer sv = xed.getInternalSourceViewer();
				XtextSourceViewer xsv = (XtextSourceViewer) sv;
				XtextDocument doc = (XtextDocument) xsv.getDocument();
				doc.readOnly(new IUnitOfWork.Void<XtextResource>() {
					public void process(XtextResource resource) throws Exception {
						
						IParseResult parseResult = resource.getParseResult();
						EObject root = parseResult.getRootASTElement();
						QueryPlan queryPlan = new QueryPlan();
						if (!QueryUtils.isQuery(root)) throw new Exception("Not a query");
						queryPlan.generatePlan((Query) root);
						queryPlan.executePlan((Query) root);
						
					
					}
						
					});
				System.out.println(doc.getClass().getName());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		
		
		
		
		MessageDialog.openInformation(window.getShell(), "Semanticworkbench",
		"Query run");
	}

	public void selectionChanged(IAction arg0, ISelection arg1) {
		// TODO Auto-generated method stub

	}

}
